class Raid < ActiveRecord::Base
  belongs_to :zone
  has_many :attendances, :dependent => :destroy
  has_many :raid_events, :dependent => :destroy
  has_many :item_drops, :dependent => :destroy
  has_many :characters, :through => :attendances, :uniq => true

  class << self
    def default_events
      #TODO: need something more elegant here.  "if e" is because
      #the test database won't have the default events unless the fixture has been
      #loaded.  Also should be configurable
      ev = []
      e = HoursEvent.find(:first)
      if e
        ev << e
      end

      e = Event.find_by_name("Sign-up Bonus")
      if e
        ev << e
      end

      return ev
    end
  end

  def after_initialize
    if @new_record
      build_default_events
    end
  end
  
  def startdate=(start)
    self["startdate"] = start
    # raid_events[0].time = start
    # raid_events[1].time = start
    raid_events.each do |raid_event|
      if raid_event.event.name == "Sign-up Bonus" or raid_event.event.name == "Hours"
        raid_event.time = start
      end
    end
  end

  def attend(character, jointime, leavetime)
    Attendance.with_scope(:create => {:jointime => jointime, :leavetime => leavetime}) do
      characters << character
    end
  end

  def generate_attendance
    raid_events.each do |re|
      re.generate_attendance
    end
  end

  def build_default_events
    Raid.default_events().each do |e|
      re = RaidEvent.new
      re.event = e
      re.time = startdate
      re.raid = self
      raid_events << re
    end
  end


end
